package com.lizheng.yunservice.wx.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.dev33.satoken.stp.StpUtil;
import com.lizheng.yunservice.common.domain.ApiRestResponse;
import com.lizheng.yunservice.common.domain.DeviceType;
import com.lizheng.yunservice.common.domain.LoginUser;
import com.lizheng.yunservice.common.exception.ServiceException;
import com.lizheng.yunservice.common.helper.LoginHelper;
import com.lizheng.yunservice.wx.domain.WxUser;
import com.lizheng.yunservice.wx.domain.bo.WxUserLoginBo;
import com.lizheng.yunservice.wx.domain.vo.Code2SessionVo;
import com.lizheng.yunservice.wx.service.IWxUserService;
import com.lizheng.yunservice.wx.service.MinProgramService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 47967
 */
@Slf4j
@Service
@AllArgsConstructor
public class MinProgramServiceImpl implements MinProgramService {

	private final WxMaService wxMaService;
	private final IWxUserService wxUserService;

	@Override
	public Code2SessionVo code2Session(HttpServletRequest request, WxUserLoginBo loginBo) throws Exception {
        WxMaConfigHolder.set(loginBo.getAppid());
        WxMaUserService maUserService = wxMaService.getUserService();
		WxMaJscode2SessionResult session = maUserService.getSessionInfo(loginBo.getJsCode());
		if(session == null || StringUtils.isEmpty(session.getOpenid())) {
			throw new ServiceException("解析code2Session失败", ApiRestResponse.FAIL);
		}
		Code2SessionVo msg = new Code2SessionVo();
		msg.setOpenId(session.getOpenid());

		//如果微信用户信息没有资料、默认注册一个
		WxUser wxUser = wxUserService.getWxUserByOpenId(msg.getOpenId());
		if(wxUser == null) {
            wxUser = new WxUser();
            wxUser.setAppId(wxMaService.getWxMaConfig().getAppid());
            wxUser.setOpenId(msg.getOpenId());
            wxUser.setUnionId(session.getUnionid());
            wxUserService.saveWxUser(wxUser);
		}


        // 生成token
        LoginUser loginUser = buildLoginUser(wxUser);
        LoginHelper.loginByDevice(loginUser, DeviceType.XCX);

        msg.setToken(StpUtil.getTokenValue());
        msg.setWxUser(wxUser);
        return msg;
	}

    /**
     * 构建登录用户
     */
    private LoginUser buildLoginUser(WxUser wxUser) {
        LoginUser loginUser = new LoginUser();
        loginUser.setWxUserId(wxUser.getWxUserId());
        loginUser.setUserId(wxUser.getWxUserId());
        loginUser.setOpenid(wxUser.getOpenId());
        loginUser.setAvatar(wxUser.getAvatarUrl());
        loginUser.setNickName(wxUser.getNickName() == null? "" : wxUser.getNickName());
        loginUser.setMobile(wxUser.getMobile());
        return loginUser;
    }
}
